package com.company.controller;

import javax.sound.midi.Soundbank;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.SocketHandler;

/**
 * 集合来不安全的问题
 * @ProjectName: 复习java
 * @Package: com.company.controller
 * @ClassName: ContainerNotSafeDemo
 * @Author: wym
 * @Date: 2020/10/13 16:13
 * @Version: 1.0
 */
public class ContainerNotSafeDemo {
    public static void main(String[] args) {
//        List<String> list = Arrays.asList("a","b","c");
//        list.forEach((i)-> System.out.println(i));
//        List<String> list=new ArrayList<>();
        //解决并发 方法 1 List<String> list=new Vector<>();
        // 解决并发 方法 2  List<String> list=Collections.synchronizedList(new ArrayList<>());
        //
        //List<String> list=new ArrayList<>();
        //解决并发  方法3
//        List<String> list=new CopyOnWriteArrayList<>();
//        for (int i = 1; i <= 30; i++)
//        {
//            new Thread(()->{
//                list.add(UUID.randomUUID().toString().substring(0,8));
//                System.out.println(list);
//            },String.valueOf(i)).start();
//        }
          Map<String,String> map= new ConcurrentHashMap<>();
        for (int i = 1; i <= 30; i++)
        {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }


    }


    public static  void  listNotSafe(){
        //解决并发 方法 1 List<String> list=new Vector<>();
        // 解决并发 方法 2  List<String> list=Collections.synchronizedList(new ArrayList<>());
        //
        //List<String> list=new ArrayList<>();
        List<String> list=new CopyOnWriteArrayList<>();
        for (int i = 1; i <= 30; i++)
        {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }

    public static void  setNotSafe(){
        // HashSet 底层是 hashmap()   value() 是一个 new Object()
        // Set<String> set=new HashSet<>();
        //底层还是 CopyOnWriteArraySet 还是  CopyOnWriteArrayList<>();
        Set<String> set=new CopyOnWriteArraySet<>();
        for (int i = 1; i <= 30; i++)
        {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }

}
